package com.atguigu.pool;

import java.util.concurrent.*;
//AbortPolicy（默认）：抛出RejectedExecutionException
//CallerRunsPolicy：由调用线程直接执行任务
//DiscardPolicy：直接丢弃任务
//DiscardOldestPolicy：丢弃队列中最旧的任务，然后重试
public class ThreadPoolDemo
{
    public static void main(String[] args)
    {
        ExecutorService threadPool = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors() + 1,
                1L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        try
        {
            for (int i = 1; i <= 10; i++) { //5个顾客（请求线程）来办理业务
                int finalI = i;
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t"+"为："+ finalI +"\t客户办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }

    private static void defaultPool()
    {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池固定数
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1线程
        //ExecutorService threadPool = Executors.newCachedThreadPool();//一池N线程

        try
        {
            for (int i = 0; i < 10; i++) { //20个顾客（请求线程）来办理业务
                int fin = i;
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"为："+ fin +"\t客户办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
